package com.company.project.service.impl.inventory;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.project.command.inventory.InventoryCommand;
import com.company.project.command.inventory.InventoryCreateOrUpdateCommand;
import com.company.project.entity.inventoryLocation.InventoryLocation;
import com.company.project.exception.NormalException;
import com.company.project.mapper.InventoryMapper;
import com.company.project.service.HttpSessionService;
import com.company.project.service.inventory.InventoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.List;

@Service
public class InventoryServiceImpl extends ServiceImpl<InventoryMapper, InventoryLocation> implements InventoryService {
    @Autowired
    private InventoryMapper inventoryMapper;

    @Autowired
    private HttpSessionService sessionService;


    @Override
    public IPage<InventoryLocation> selectselectAllTables(InventoryCommand command) {
        Page<InventoryLocation> page = new Page<>();
        //分页

        command.setPage((command.getPage() - 1) * command.getlimit());

        List<InventoryLocation> inventoryLocations = inventoryMapper.selectTables(command);
        int count = inventoryMapper.selectCount(command);
        page.setRecords(inventoryLocations);
        page.setTotal(count);
//        page.setSize(command.getlimit());
//        page.setCurrent(command.getPage());
        return page;
    }

    @Override
    public void create(InventoryCreateOrUpdateCommand command) {
        LambdaQueryWrapper<InventoryLocation> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(InventoryLocation::getWarehouseId, command.getId());
        queryWrapper.eq(InventoryLocation::getInventoryLocationNo, command.getInventoryLocationNo());
        if (this.inventoryMapper.selectOne(queryWrapper) != null) {
            throw new NormalException("库位号已经存在，操作异常");
        }
        InventoryLocation inventory = new InventoryLocation();

        inventory.setWarehouseId(command.getWarehouseId());
        inventory.setRegion(command.getRegion());
        inventory.setInventoryLocationNo(command.getInventoryLocationNo());
        inventory.setEnabled(true);
        inventory.setCreatedDate(Calendar.getInstance().getTime());
        inventory.setLastModifiedDate(inventory.getCreatedDate());
        inventory.setCreatedBy(sessionService.getCurrentUsername());
        inventory.setOwner(command.getOwner());
        this.inventoryMapper.insert(inventory);

    }
}
